package cn.stylefeng.qz.core.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @description 
 * @author qinj
 * @date 2019/3/11 12:40
 * @since 
 */
public class NumberUtils {

    /**
     * @description 四舍五入
     * @author qinj
     * @since 2019/3/11 12:41
     * @version 1.3.3.1
     * @param number      目标
     * @param sDecimalLen 小数位数
     */
    public static float round(Number number, int sDecimalLen) {
        if(sDecimalLen == 0)
            return Math.round(number.floatValue());
        int rate = 1, step = 10;
        for (int index = 0; index < sDecimalLen; index++) {
            rate = step * rate;
        }
        Integer value = Math.round(number.floatValue() * rate);
        System.out.println(value);
        return value.floatValue() / rate ;
    }

    /**
     * @description 四舍五入
     * @author qinj
     * @since 2019/3/28 10:11
     * @version 1.3.4
     */
    public static double numberRound(double number) {
        BigDecimal b = new BigDecimal(number);
        number = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return number;
    }

    public static String numberRoundStr(double number) {
        DecimalFormat df   = new DecimalFormat("######0.00");
        return df.format(number);
    }

    public static double numberRound(double number, int scale) {
        BigDecimal b = new BigDecimal(number);
        number = b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        return number;
    }

    public static float numberRound(float number, int scale) {
        BigDecimal b = new BigDecimal(number);
        number = b.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue();
        return number;
    }

    public static double add(Double number1, Double number2, int scale) {
        BigDecimal b1 = new BigDecimal(number1 == null ? 0 : number1);
        BigDecimal b2 = new BigDecimal(number2 == null ? 0 : number2);
        return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static double sub(Double number1, Double number2, int scale) {
        BigDecimal b1 = new BigDecimal(number1 == null ? 0 : number1);
        BigDecimal b2 = new BigDecimal(number2 == null ? 0 : number2);
        return b1.subtract(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
